//
//  AiSetViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/8.
//

import Foundation
import LeanCloud
import SwiftUI

/**
 *  ai设置
 */
class AiSetViewModel : BaseViewModel {
    @Published var items = [AiRoleBean]()
    @Published var isLoading = true
    @Published var callTimeStart: Int = 3600 * 9//拨打电话时间
    @Published var callTimeEnd: Int = 3599 * 24//拨打电话时间
    @Published  var isAiVisible = false
    private let tag = "aiset"

    override init() {
        super.init()
        self.addObserve(self, .updateAiRole) { (selfInstance, update: Bool) in
            //刷新ai列表
            selfInstance.items.removeAll()
            selfInstance.getSystemAiRoleList()
        }
    }
    
    //来电配置
    func getTimeData() {
        request(isLoading: false) {
            let config = try await BackupsManager.shared.getDelegateConfig()?.getFolderConfig() ?? FolderConfig()
            return config
        } suc: {
            self.callTimeStart = $0.callTimeStart
            self.callTimeEnd =  $0.callTimeEnd
        } fail: {_ in
        }
    }

    func getTimePeriod(_ seconds: Int)-> String {
        let hours = seconds / 3600
        let minutes = (seconds % 3600) / 60
        return String(format: "%02d:%02d", hours, minutes)
    }
    
    func doSaveCallTime() {
        request {
            let config = try await BackupsManager.shared.getDelegateConfig()?.getFolderConfig()
            if let config = config {
                config.callTimeStart = self.callTimeStart
                config.callTimeEnd = self.callTimeEnd
                try await BackupsManager.shared.getDelegateConfig()?.saveFolderConfig(bean: config)
            }
        } suc: {
            showToast("保存成功")
            TaskCallExt.instance.updateTask()
        } fail: {
            showToast($0.message)
        }
    }
    
    
    func getSystemAiRoleList() {
        showLog("查询系统角色")
        request(isLoading: false) {
            try await BackupsManager.shared.getDelegateConfig()?.getAiRoleList(true) ?? []
        } suc: {
            self.isLoading = false
            self.items = $0
            showLog($0)
        } fail: {
            self.isLoading = false
            let toast = $0.message
            showLog("获取系统角色列表报错：\(toast)")
            showToast(toast)
        }
    }
    
    func doVoiceTest() {
        request {
            let query = LCQuery(className: "VoiceTest")
            let list = try await LeancloudManager.instance.getList(query: query, modeType: VoiceTestBean.self)
            try check(!list.isEmpty) {
                "暂时无法试听"
            }
            //随机一个
            if let bean = list.randomElement() {
                let (hexString, hexData) = try await AiChatExt.doAiVoiceTest(text: bean.text, voiceId: bean.voiceId, voiceHex: bean.voiceHex)
                if ((bean.voiceHex ?? "").isEmpty && (bean.text?.count ?? 0) < 130) {
                    //保存起来，下次就不需要了
                    bean.voiceHex = hexString
                    try await LeancloudManager.instance.save(todo: bean)
                }
                return (bean, hexData)
            } else {
                throw MyError.checkParameter(self.tag, "暂时无法试听")
            }
           
        } suc: { (bean , hexData) in
            //唤起语音播放界面
            let callParam : VoiceCallParam = VoiceCallParam()
            callParam.hexData = hexData
            callParam.isStart = false
            callParam.logo = bean.avatar
            callParam.showName = bean.name
            commonManager.showVoiceWaitDialog(callParam)
        } fail: {
            showToast($0.message)
        }
    }
}
